package prosync;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.Watcher.Event.EventType;
import org.apache.zookeeper.Watcher.Event.KeeperState;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * 配置中心
 *
 * @author wangjinqiang
 * @date 2019-08-05
 */
public class ZookeeperProSync {
    /**
     * 用于等待 Zookeeper 连接成功
     */
    private static CountDownLatch connectedCL = new CountDownLatch(1);
    private static ZooKeeper zk = null;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
        String path = "/username";
        zk = new ZooKeeper("127.0.0.1:2181", 5000, event -> {
            // zk 连接成功通知事件
            if (event.getState() == KeeperState.SyncConnected) {
                if (EventType.None == event.getType() && event.getPath() == null) {
                    connectedCL.countDown();
                } else if (event.getType() == EventType.NodeDataChanged) {
                    // zk 目录节点数据变化通知
                    try {
                        System.out.println("配置已修改为新值： " + new String(zk.getData(path, true, stat)));
                    } catch (KeeperException | InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        connectedCL.await();
        System.out.println(new String(zk.getData(path, true, stat)));
        Thread.sleep(Integer.MAX_VALUE);
    }

}
